package com.jplus.mvc.web;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.jplus.core.anno.boot.Bean;
import com.jplus.core.anno.boot.ComponentScan;
import com.jplus.core.anno.boot.Configuration;
import com.jplus.core.anno.boot.PropertySource;
import com.jplus.core.core.abstracts.Environment;
import com.jplus.core.db.JdbcTemplate;
import com.jplus.core.plugin.async.EnableAsync;
import com.jplus.core.plugin.scheduling.EnableScheduling;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;

@Configuration
@ComponentScan("com.jplus.mvc")
@PropertySource("file:/config/jplus-mvc.properties")
@EnableAsync
@EnableScheduling
public class WebConfig {

	@Bean(destroyMethod = "close")
	public HikariDataSource hikariDataSource(Environment env) {
		HikariConfig conf = new HikariConfig();
		conf.setDriverClassName("com.mysql.jdbc.Driver");
		conf.setJdbcUrl(env.getProp("dataSource.jdbcUrl"));
		conf.setUsername(env.getProp("dataSource.username"));
		conf.setPassword(env.getProp("dataSource.password"));
		HikariDataSource dataSource = new HikariDataSource(conf);
		return dataSource;
	}

	@Bean
	public JdbcTemplate jdbcTemplate(HikariDataSource hikariDataSource) {
		return new JdbcTemplate(hikariDataSource);
	}

	@Bean(destroyMethod = "shutdown")
	public RedisClient redisClient(Environment env) {
		// client
		return RedisClient.create(env.getProp("redis.lettuce.uri"));
	}

	@Bean(destroyMethod = "close")
	public StatefulRedisConnection<String, String> connection(RedisClient redisClient) {
		// connect
		return redisClient.connect();
	}

	// * 对于线程池这种东西，最好加上销毁方法调用
	@Bean(value = "fixedThreadPool", destroyMethod = "shutdownNow")
	public ExecutorService executorService() {
		return Executors.newFixedThreadPool(10);// 创建一个定长的线程池
	}

}
